<template>
  <FModal width="1200" header="角色管理" ref="refFModal">
    <FPage>
      <template #header>
        <div style="padding: 5px">
          <el-form class="role-manager-body-search simple-line-form" style="height: 30px"
                   inline ref="searchForm" status-icon :rules='[]' :model="searchParams">
            <el-form-item prop="roleName" label="角色名称">
              <el-input placeholder="请输入角色名称" style="width: 120px" v-model="searchParams.roleName"/>
            </el-form-item>
            <el-form-item prop="roleCode" label="角色编码">
              <el-input placeholder="请输入角色编码" style="width: 120px" v-model="searchParams.roleCode"/>
            </el-form-item>
            <el-form-item prop="roleCode" label="默认">
              <SystemDict placeholder="默认" style="width: 80px" dict-code="yesOrNot"
                          v-model="searchParams.roleDefault"/>
            </el-form-item>
            <el-form-item prop="roleStatus" label="状态">
              <SystemDict placeholder="请选择状态" style="width: 120px" dict-code="roleStatus"
                          v-model="searchParams.roleStatus"/>
            </el-form-item>
            <el-form-item prop="roleType" label="角色类型">
              <SystemDict placeholder="请选择角色类型" style="width: 120px" dict-code="roleType"
                          v-model="searchParams.roleType"/>
            </el-form-item>
            <el-form-item style="margin-left: 10px">
              <el-button round type="primary" icon="search" @click="search"/>
              <el-button round icon="add" @click="addNew"/>
              <el-button round type="warning" icon="remove" @click="removeRole"
                         :disabled="!removeAble"/>
              <el-button round icon="setting" :disabled="!removeAble"
                         @click="configMenus">分配菜单
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>

      <div class="role-manager-body">
        <FPage style="background: white">
          <template #header>
            <el-tabs class="simple-line-tabbs designer-container-header"
                     v-model="showPanel" @tab-change="showPanelChange">
              <el-tab-pane class="" name="unitRole" label="单位角色">
              </el-tab-pane>

              <el-tab-pane class="" name="departRole" label="部门角色">
              </el-tab-pane>
            </el-tabs>
          </template>
          <el-table height="100%" border stripe :default-sort="sortConfig" @row-click="rowClick"
                    :data="dataSource" @sort-change="sortChange" @selection-change="selectionChange"
                    v-loading="loading">
            <el-table-column type="selection" width="40"/>
            <el-table-column sortable show-overflow-tooltip prop="roleName" label="角色名称"/>
            <el-table-column sortable show-overflow-tooltip prop="roleCode" label="角色编码"/>
            <el-table-column sortable show-overflow-tooltip prop="sort" label="排序号"/>
            <el-table-column show-overflow-tooltip prop="departRole" label="角色所属">
              <template #default="{row}">
                <SystemDict v-model="row.departRole" :disabled="true" dict-code="departRole"/>
              </template>
            </el-table-column>

            <el-table-column sortable show-overflow-tooltip prop="departRole" label="状态">
              <template #default="{row}">
                <SystemDict v-model="row.roleStatus" :disabled="true" dict-code="roleStatus"/>
              </template>
            </el-table-column>

            <el-table-column sortable show-overflow-tooltip prop="roleDefault" label="默认角色">
              <template #default="{row}">
                <SystemDict v-model="row.roleDefault" :disabled="true" dict-code="booleanYesNot"/>
              </template>
            </el-table-column>

            <el-table-column sortable show-overflow-tooltip prop="roleType" label="角色类型">
              <template #default="{row}">
                <SystemDict v-model="row.roleType" :disabled="true" dict-code="roleType"/>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip prop="departRole" label="单位/部门管理页显示">
              <template #default="{row}">
                <SystemDict v-model="row.showInUnitManagePage" :disabled="true" dict-code="booleanYesNot"/>
              </template>
            </el-table-column>
            <el-table-column sortable show-overflow-tooltip prop="roleDesc" label="说明"/>
          </el-table>
        </FPage>
      </div>

      <template #footer>
        <div style="display: flex; padding: 5px; justify-content: end">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="pageOptions"
            background layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total" small
            @size-change="search"
            @current-change="pageChange"
          />
        </div>
      </template>
    </FPage>
    <template #footer>
      <el-button icon="close" round type="warning" @click="close">关闭</el-button>
    </template>
  </FModal>
  <RoleEditModal @saved="saved" ref="refRoleEditModal"/>
  <MenuConfigModal ref="refMenuConfigModal"/>
</template>
<script setup>
import FModal from '@/components/FModal/index.vue';
import {computed, nextTick, ref, shallowRef} from 'vue';
import FPage from '@/components/layout/FPage.vue';
import TableSearchUtils from '@/utils/TableSearchUtils';
import SystemDict from '@/components/SystemDict/index.vue';
import RoleEditModal from '@/views/system/UnitManagement/RoleManagerModal/RoleEditModal.vue';
import {real} from '@/utils/CommonUtils';
import {deleteAction, getAction} from '@/request/BaseRequest';
import MenuConfigModal from '@/views/system/UnitManagement/MenuConfigModal/index.vue';
import {ElMessage, ElMessageBox} from 'element-plus';

const refFModal = shallowRef();
const refMenuConfigModal = shallowRef();
const searchForm = shallowRef();
const refRoleEditModal = shallowRef();
const searchParams = ref({});
const showPanel = shallowRef('unitRole');
let unitData = undefined;

function setData(_unitData) {
  unitData = _unitData;
  refFModal.value.open();
  nextTick(search);
}

function removeRole() {
  let id = real(selectedRows)[0].id;
  loading.value = true;
  getAction('/sys/role/canRemove', {id}).then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      if (result.canRemove) {
        ElMessageBox.confirm('删除后不可恢复, 确定删除吗', '确定删除?', {
          draggable: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          doRemove(id);
        }).catch(() => {
        });
      } else {
        ElMessage({
          message: result.message,
          type: 'warning',
        });
      }
    }
  });
}

function doRemove(id) {
  loading.value = true;
  deleteAction('/sys/role/remove', {id}).then(data => {
    loading.value = false;
    if (data.success) {
      search(true);
    }
  });
}

function configMenus() {
  refMenuConfigModal.value.setData(real(selectedRows)[0]);
}

function addNew() {
  refRoleEditModal.value.setData(unitData);
}

function showPanelChange() {
  nextTick(search);
}

function saved() {
  search(true);
}

function doSearch(params) {
  params = real(params);
  params.unitId = real(unitData).id;
  if (showPanel.value === 'unitRole') {
    params.departRole = false;
  } else {
    params.departRole = true;
  }

  loading.value = true;
  getAction('/sys/role/searchRoles', params).then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      setSearchResult(result);
    }
  });
}

function onSelection() {

}

function onRowClick(row) {
  refRoleEditModal.value.setData(unitData, row);
}

const removeAble = computed(() => {
  try {
    return selectedRows.value.length === 1;
  } catch (e) {
  }
  return false;
});

function close() {
  refFModal.value.close();
}

const {
  loading, rowClick, search, selectionChange, setSearchResult, pageOptions, pageChange,
  sortChange, dataSource, resetQueryParams, sortConfig, selectedRows, pagination
} = TableSearchUtils({
  refForm: searchForm,
  doSearch,
  defaultSortConfig: {
    prop: undefined,
    order: undefined,
  },
  searchParams,
  selectionChange: onSelection,
  rowClick: onRowClick
});

defineExpose({
  setData
});
</script>
<script>
export default {
  name: 'RoleManagerModal'
};
</script>
<style>
.role-manager-body {
  background: white;
  overflow: auto;
}

.f-modal-body .role-manager-body {
  height: 600px;
}

.f-modal-fullscreen-body .role-manager-body {
  height: 100%;
}

.role-manager-body-search label {
  margin: 0;
  padding: 0 5px;
}
</style>
